import React from 'react';
import ReactDOM from 'react-dom/client';
import { Validate, ValidateRule, DictData } from '../types';
import { apiGetDictDataList } from '../api';
import { Message, Tag } from '@arco-design/web-react';
import regionData from './region.json';
import dayjs from 'dayjs';

export function dictDataOptions(list: any) {
  let options: { label: string; value: string }[] = [];
  let _list = list ?? [];
  if ((_list.length || 0) > 0) {
    _list.forEach((i: DictData) => {
      options.push({ label: i.dictLabel!, value: i.dictValue! });
    });
  }
  return options;
}
/**
 * 把对象的Key按字典排序并转成字符串
 * @param obj 数据
 * @returns string
 */
export function objectSortToString(obj: any): string {
  if (obj === undefined || obj === null) return '';
  if (typeof obj === 'string') return 'str:' + obj;
  if (typeof obj === 'boolean') return 'bool:' + obj.toString();
  if (typeof obj === 'number') return 'num:' + obj.toString();
  let keys = Object.keys(obj);
  if (!keys.length) return '{}';
  keys.sort();
  let map: any = {};
  for (let key of keys) {
    let s = objectSortToString(obj[key]);
    map[key] = s;
  }
  return JSON.stringify(map);
}
// 流量转换 K -> G
export function flowKTOG(v?: number) {
  if ((v ?? 0) === 0) return 0;
  return v! / 1024 / 1024;
}
export function rpx(t: number): number {
  return (t / 375) * window.innerWidth;
}
// 城市列表
export function cityList(province?: string): string[] {
  if (province) {
    let _province = regionData.find((i) => i.label === province);
    if (_province) {
      return _province.children.map((i) => i.label);
    }
  }
  let _list: string[] = [];
  regionData.forEach((i) => {
    _list = _list.concat(i.children.map((c) => c.label));
  });
  return _list;
}
export function randomString(len?: number) {
  len = len || 32;
  let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678oOLl9gqVvUuI1';
  let maxPos = $chars.length;
  let pwd = '';
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

/** 字典内容显示TAG */
export function dictTag(v: any, list?: DictData[], bordered?: boolean) {
  let _r = (list ?? []).find((i) => (i.dictValue ?? '').toString() === (v ?? '').toString());
  if (!_r) return null;
  return (
    <Tag key={v} bordered={bordered} color={findTagColor(_r?.listClass)}>
      {_r?.dictLabel}
    </Tag>
  );
}
// tag颜色选项
export const tagStyleOptions = [
  { label: '主色(arcoblue)', value: 'arcoblue' },
  { label: '成功(green)', value: 'green' },
  { label: '信息(cyan)', value: 'cyan' },
  { label: '错误(red)', value: 'red' },
  { label: '警告(orangered)', value: 'orangered' },
  { label: 'magenta', value: 'magenta' },
  { label: 'orange', value: 'orange' },
  { label: 'gold', value: 'gold' },
  { label: 'lime', value: 'lime' },
  { label: 'blue', value: 'blue' },
  { label: 'purple', value: 'purple' },
  { label: 'pinkpurple', value: 'pinkpurple' },
  { label: 'gray', value: 'gray' },
  { label: 'black', value: 'black' },
  { label: 'darkgray', value: 'darkgray' },
];
// tag 颜色转换
export function findTagColor(color?: string) {
  if (!color) return 'arcoblue';
  let v = tagStyleOptions.find((i) => i.value === color);
  if (v) return v.value;
  if (color === 'default') return 'arcoblue';
  if (color === 'primary') return 'arcoblue';
  if (color === 'success') return 'green';
  if (color === 'error' || color === 'danger') return 'red';
  if (color === 'warning') return 'orangered';
  if (color === 'info') return 'cyan';
  return color;
}

export async function getDict(...list: string[]) {
  let _list = list ?? [];
  // 显式声明 data 的类型，支持字符串索引
  const data: { [key: string]: DictData[] } = {};
  if ((_list.length || 0) > 0) {
    for (const i of _list) {
      if (i && i && apiGetDictDataList) {
        const res = await apiGetDictDataList(i);
        data[i] =  res?.data?.rows || [];
      }
    }
  }
  return data;
}
// 延迟执行
export function delay(ms: number): Promise<void> {
  return new Promise<void>((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, ms);
  });
}
// 县/区列表
export function areaList(province?: string, city?: string): string[] {
  let _province = regionData.find((i) => i.label === province);
  if (province && _province) {
    let _city = _province.children.find((c) => c.label === city);
    if (city && _city) {
      return _city.children.map((a) => a.label);
    } else {
      let _list: string[] = [];
      _province.children.forEach((c) => {
        _list = _list.concat(c.children.map((a) => a.label));
      });
      return _list;
    }
  }
  let _list: string[] = [];
  regionData.forEach((i) => {
    i.children.forEach((c) => {
      _list = _list.concat(c.children.map((a) => a.label));
    });
  });
  return _list;
}
// 省份列表
export function provinceList(all?: boolean): string[] {
  let _list = regionData.map((i) => i.label);
  if (all) {
    _list.unshift('全国');
  }
  return _list;
}
export function isArray(arg: any): boolean {
  if (typeof Array.isArray === 'undefined') {
    return Object.prototype.toString.call(arg) === '[object Array]';
  }
  return Array.isArray(arg);
}
function BottomBox({ content }: { content: React.ReactNode }) {
  return (
    <div className="bottom-box">
      <div className="flex-1"></div>
      <div className="content bw-100">{content}</div>
    </div>
  );
}

export function showBottom(buildContent: (onOk: (value: unknown) => void) => React.ReactNode): Promise<any> {
  return new Promise((resolve) => {
    const div = document.createElement('div');
    document.body.appendChild(div);
    const root = ReactDOM.createRoot(div);
    const onOk = (v: any) => {
      document.body.removeChild(div);
      resolve(v);
    };
    root.render(<BottomBox content={buildContent(onOk)} />);
  });
}
// 深拷贝
export function cloneDeep(obj: any) {
  if (typeof obj !== 'object') return obj;
  return JSON.parse(JSON.stringify(obj));
}
export function clearEmptyKey(params: any) {
  let _p = cloneDeep(params);
  Object.keys(_p).forEach((i) => {
    if (_p[i] == null || _p[i] === '' || _p[i] === undefined) {
      delete _p[i];
    } else if (typeof _p[i] === 'object') {
      if (_p[i] instanceof Object) {
        _p[i] = clearEmptyKey(_p[i]);
      }
      if (!Object.keys(_p[i]).length) {
        delete _p[i];
      }
    }
  });
  return _p;
}
interface ConfirmBoxProps {
  title?: string;
  content: React.ReactNode;
  hideConfirmBtn?: boolean;
  hideCancelBtn?: boolean;
  confirmBtnText?: string;
  cancelBtnText?: string;
  onConfirm: () => void;
  onCancel: () => void;
}

// 字段规则验证
export function validateField(data: any, rules: ValidateRule) {
  const numberReg = /^\d+(\.\d+)?$/;
  let map: { [x: string]: any } = {};
  let fields: string[] = Object.keys(rules);

  for (let field of fields) {
    let _rule = rules[field];
    let validateData = (data ?? {})[field];
    if (typeof _rule === 'boolean') {
      // 检测到 _obj:true 本项不处理
      continue;
    }

    if (typeof _rule !== 'string' && _rule._obj) {
      let _map = validateField(validateData, _rule as ValidateRule);
      if (Object.keys(_map).length) {
        _map._obj = true;
        map[field] = _map;
      }
      continue;
    }

    let rule: Validate = _rule as Validate;
    let mastCheck = false;
    if (typeof rule.required === 'string') {
      // 依赖于 某个字段等于某个值 可以用`逗号[,]`分割多个字段，只要有一个依赖字段的值符合并且自身为空 就显示错误
      // 依赖于 某个字段等于某个值 可以用`和号[&]`分割多个字段，需要全部的依赖字段的值符合并且自身为空 就显示错误

      // required 内有逗号 检测多个字段
      if (rule.required.includes(',')) {
        let requiredFields = rule.required.split(',');
        for (let requiredField of requiredFields) {
          if (rule[requiredField] === undefined) {
            // 只要求依赖字段不能为空
            if (data[requiredField] !== undefined && data[requiredField] !== '' && data[requiredField] !== null) {
              mastCheck = true;
            }
          } else if (rule[requiredField].includes(',')) {
            // 如果依赖字段的值是包含逗号分割的多个值，则只要符合其中一项且自身为空，就显示错误
            for (let requiredFieldValue of rule[requiredField].split(',')) {
              if (data[requiredField] === requiredFieldValue) {
                mastCheck = true;
                break;
              }
            }
          } else if (data[requiredField] === rule[requiredField]) {
            // 依赖的字段等于某个具体的值
            mastCheck = true;
          }
        }

        // required 内有和号 检测多个字段
      } else if (rule.required.includes('&')) {
        mastCheck = true;
        let requiredFields = rule.required.split('&');
        for (let requiredField of requiredFields) {
          // 只要求依赖字段不能为空
          if (rule[requiredField] === undefined) {
            if (data[requiredField] !== undefined && data[requiredField] !== '' && data[requiredField] !== null) {
              mastCheck = true;
            }
          }
          if (rule[requiredField].includes(',')) {
            // 如果依赖字段的值是包含逗号分割的多个值，则只要符合其中一项且自身为空，就显示错误
            for (let requiredFieldValue of rule[requiredField].split(',')) {
              if (data[requiredField] === requiredFieldValue) {
                mastCheck = true;
                break;
              }
            }
          } else if (data[requiredField] !== rule[requiredField]) {
            // 如果要求的字段不为空又不等于要求的值 则不检测
            mastCheck = false;
          }
        }

        // required 内没有逗号和号 检测单个字段
      } else {
        /// 只要求依赖字段不能为空
        if (rule[rule.required] === undefined) {
          if (data[rule.required] !== undefined && data[rule.required] !== '' && data[rule.required] !== null) {
            mastCheck = true;
          }
        } else if (rule[rule.required].includes(',')) {
          // 如果依赖字段的值是包含逗号分割的多个值，则只要符合其中一项且自身为空，就显示错误
          for (let requiredFieldValue of rule[rule.required].split(',')) {
            if (data[rule.required] === requiredFieldValue) {
              mastCheck = true;
              break;
            }
          }
        } else if (data[rule.required] === rule[rule.required]) {
          /// 依赖的字段的值等于该字段的值
          mastCheck = true;
        }
      }
    } else if (typeof rule.required === 'boolean' && rule.required) {
      mastCheck = true;
    }

    if (mastCheck) {
      if (rule.bool === true) {
        if (validateData !== true && validateData !== false) {
          map[field] = rule.message;
        }
      } else if (rule.number === true) {
        if ((!validateData && validateData !== 0) || !numberReg.test(validateData)) {
          map[field] = rule.message;
        }
      } else if (rule.min || rule.min === 0) {
        if (validateData * 1 < rule.min!) {
          map[field] = rule.message;
        }
      } else if (rule.max || rule.max === 0) {
        if (validateData * 1 > rule.max!) {
          map[field] = rule.message;
        }
      } else if (rule.minLength || rule.minLength === 0) {
        if ((validateData + '').length < rule.minLength) {
          map[field] = rule.message;
        }
      } else if (rule.maxLength || rule.maxLength === 0) {
        if ((validateData + '').length > rule.maxLength) {
          map[field] = rule.message;
        }
      } else if (rule.regexp) {
        if (!rule.regexp!.test(validateData)) {
          map[field] = rule.message;
        }
      } else if (!validateData) {
        map[field] = rule.message;
      }
    }
  }
  return map;
}
function ConfirmBox({
  title,
  content,
  hideConfirmBtn,
  hideCancelBtn,
  confirmBtnText,
  cancelBtnText,
  onConfirm,
  onCancel,
}: ConfirmBoxProps) {
  return (
    <div className="confirm-box">
      <div className="content">
        <div className="p-10 font-widget-600 font-size-16">{title ?? '提示'}</div>
        <div className="text">{content}</div>
        <div className="d-flex-r border-top bw-100">
          {!hideCancelBtn && (
            <div className="flex-1 p-10 text-center border-right" onClick={onCancel}>
              {cancelBtnText ?? '取消'}
            </div>
          )}
          {!hideConfirmBtn && (
            <div className="flex-1 p-10 text-center text-color-p" onClick={onConfirm}>
              {confirmBtnText ?? '确定'}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export async function showConfirm({
  title,
  content,
  hideConfirmBtn,
  hideCancelBtn,
  confirmBtnText,
  cancelBtnText,
}: ConfirmBoxProps): Promise<any> {
  return new Promise((resolve) => {
    const div = document.createElement('div');
    document.body.appendChild(div);
    const root = ReactDOM.createRoot(div);
    const onOk = (v: any) => {
      document.body.removeChild(div);
      resolve(v);
    };
    root.render(
      <ConfirmBox
        title={title}
        content={content}
        hideConfirmBtn={hideConfirmBtn}
        hideCancelBtn={hideCancelBtn}
        confirmBtnText={confirmBtnText}
        cancelBtnText={cancelBtnText}
        onConfirm={() => onOk(1)}
        onCancel={() => onOk(0)}
      />
    );
  });
}

interface ToastBoxProps {
  msg: string;
}

function ToastBox({ msg }: ToastBoxProps) {
  return (
    <div className="toast-box">
      <div className={`toast`}>{msg}</div>
    </div>
  );
}

type ToastClose = () => void;
export function showToast(msg: string): ToastClose {
  const div = document.createElement('div');
  document.body.appendChild(div);
  const root = ReactDOM.createRoot(div);
  root.render(<ToastBox msg={msg} />);
  let ref: { root?: ReactDOM.Root; div: HTMLDivElement } = { root, div };

  setTimeout(() => {
    if (ref.root) {
      ref.root.unmount();
      document.body.removeChild(ref.div);
      ref.root = undefined;
    }
  }, 2000);
  return () => {
    if (ref.root) {
      ref.root.unmount();
      document.body.removeChild(ref.div);
      ref.root = undefined;
    }
  };
}
export function isNull(value: any): boolean {
  return value === null || value === undefined || value === '';
}

export function isString(str: any): boolean {
  if (typeof str === 'string' || str instanceof String) {
    return true;
  }
  return false;
}
/** 基本类型数组 去空 */
export function clearEmpty(list: Array<String | number>) {
  let _tmp: Array<String | number> = [];
  for (let i of list) {
    if (!!i && i !== 'undefined' && i !== 'null' && i !== 'NaN' && i.toString().length > 0) {
      _tmp.push(i);
    }
  }
  return _tmp;
}
// 解析url参数
export function parseLocationParams(params?: string): { [x: string]: string } {
  if (!params) return {};
  let real = params.startsWith('?') ? params.split('?')[1] : params;
  let _tmpList = real.split('&') || [];
  let p: { [x: string]: string } = {};
  for (let _tmp of _tmpList) {
    let [_k, _v] = _tmp.split('=');
    p[_k] = _v;
  }
  return p;
}
/**
 * 创建一个新的对象并排除参数里的属性
 */
export function omitObject(obj: { [x: string]: any }, args: string[]) {
  let _newObj: any = {};
  Object.keys(obj).forEach((k) => {
    if (!args.includes(k)) {
      _newObj[k] = obj[k];
    }
  });
  return _newObj;
}
// 基本类型数组 去重
export function clearRepeat(list: Array<string | number>) {
  let _tmp: Array<string | number> = [];
  for (let i of list) {
    if (!_tmp.includes(i)) {
      _tmp.push(i);
    }
  }
  return _tmp;
}
export function validEmail(email: string): boolean {
  const reg =
    // eslint-disable-next-line
    /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return reg.test(email);
}
export function validTel(tel: string): boolean {
  const reg = /^1[3-9]{1}[0-9]{9}$/;
  return reg.test(tel);
}
export function sumField<T>(list: T[], field: keyof T): number {
  return list.reduce((sum, item) => sum + (Number(item[field]) || 0), 0);
}
/**
 * 格式化数字为以逗号分割的字符串
 * @param num 要格式化的数字
 * @param precision 数字精度
 * @returns 格式化后的字符串
 */
export function formatNumber(num?: string | number, precision?: number) {
  let isFuShu = parseFloat((num ?? 0).toString()) < 0;
  let t: string = Math.abs(parseFloat((num ?? 0).toString())).toFixed(precision ?? 2);
  let _list = t.split('.');
  let _format = '';
  for (let i = _list[0].length - 1; i >= 0; i--) {
    if (_format.length > 0 && _format.replaceAll(',', '').length % 3 === 0) {
      _format = ',' + _format;
    }
    _format = _list[0][i] + _format;
  }
  _list[0] = _format;
  let res = _list.join('.');
  if (res.startsWith(',')) {
    res = res.substring(1);
  }
  if (res.includes('.') && res.split('.')[1] === '00') {
    res = res.split('.')[0];
  }
  if (isFuShu) {
    res = '-' + res;
  }
  return res;
}
export function maskMiddle(str: string, headLen: number = 4, tailLen: number = 4): string {
  if (!str) return '';
  if (str.length <= headLen + tailLen) return str; // 如果长度不够直接返回原字符串
  const head = str.slice(0, headLen);
  const tail = str.slice(-tailLen);
  const middle = '*'.repeat(str.length - headLen - tailLen);
  return `${head}${middle}${tail}`;
}
export class PayType {
  /// 余额支付
  static balance = 'balancePay';

  /// 官方微信支付
  static weixin = 'wechatPay';

  /// 官方支付宝支付
  static alipay = 'aliPay';

  /// 支付宝网页支付
  static aliPage = 'aliPage';

  /// 云闪付
  static unionpay = 'union_pay';

  /// HWC微信支付 拉起小程序，在小程序内拉起微信支付
  static gatherpayWechat = 'gatherPayWechat';

  /// HWC支付宝扫码支付 得到二维码内容后跳转
  static gatherpayAli = 'gatherPayAli';

  /// HWC公众号支付
  static gatherPayJsWechat = 'gatherPayJsWechat';
  /// 官方公众号支付
  static wechatJsPay = 'wechatJsPay';
  // 银联快捷
  static sdbPayFast = 'sdbPayFast';
  // 银联快捷
  static sdbPayFastWeb = 'sdbPayFastWeb';
  // 瑞生意支付 第四方 微信支付
  static gmeJsPay = 'gmeJsPay';
  // 富友公众号支付 第四方 微信支付
  static fyH5Pay = 'fyH5Pay';
  // 惠收米公众号支付 第四方微信支付
  static hsmWxJsPay = 'hsmWxJsPay';
  // 汇付 微信H5支付 第四方微信支付 斗拱
  // https://paas.huifu.com/open/service/develop/#/%E6%94%AF%E4%BB%98%E4%BA%A7%E5%93%81/%E5%BE%AE%E4%BF%A1%E5%85%AC%E4%BC%97%E5%8F%B7%E6%94%AF%E4%BB%98
  static hfH5Wx = 'hfH5Wx';
  static typeStr(type?: string) {
    if (type === PayType.balance) {
      return '余额支付';
    } else if (type === PayType.unionpay) {
      return '云闪付';
    } else if (
      type === PayType.weixin ||
      type === PayType.gatherpayWechat ||
      type === PayType.gatherPayJsWechat ||
      type === PayType.wechatJsPay ||
      type === PayType.fyH5Pay ||
      type === PayType.gmeJsPay ||
      type === PayType.hsmWxJsPay ||
      type === PayType.hfH5Wx
    ) {
      return '微信支付';
    } else if (type === PayType.alipay || type === PayType.gatherpayAli || type === PayType.aliPage) {
      return '支付宝支付';
    } else if (type === PayType.sdbPayFast || type === PayType.sdbPayFastWeb) {
      return '银联快捷';
    }
    return '';
  }

  static typeIcon(type?: string) {
    if (type === PayType.balance) {
      return './pic/icon_pay_balance.png';
    } else if (type === PayType.unionpay) {
      return './pic/icon_pay_union.png';
    } else if (type === PayType.sdbPayFast || type === PayType.sdbPayFastWeb) {
      return './pic/icon_yinlian.png';
    } else if (
      type === PayType.weixin ||
      type === PayType.gatherpayWechat ||
      type === PayType.gatherPayJsWechat ||
      type === PayType.wechatJsPay ||
      type === PayType.fyH5Pay ||
      type === PayType.gmeJsPay ||
      type === PayType.hsmWxJsPay ||
      type === PayType.hfH5Wx
    ) {
      return './pic/icon_pay_wx.png';
    } else if (type === PayType.alipay || type === PayType.gatherpayAli || type === PayType.aliPage) {
      return './pic/icon_pay_zfb.png';
    }
    return './pic/icon_pay_balance.png';
  }
}
export function isDiffMoreThanFiveMinutes(timestamp1: number, timestamp2: number): boolean {
  // 计算两个时间的差值，单位为分钟
  const diffInMinutes = Math.abs(timestamp1 - timestamp2) / 1000 / 60;
  return diffInMinutes > 5;
}
export  function getLocCardInfo(iccid: string) { 
  const newDate = dayjs().valueOf();
  
  const iccidCardList = localStorage.getItem('iccidCardList');
 
  if (iccidCardList) { 

    const iccidCardListObj = JSON.parse(iccidCardList);
    for(let i in iccidCardListObj){
      if(isDiffMoreThanFiveMinutes(newDate,iccidCardListObj[i].timer)){
        delete iccidCardListObj[i];
      }
    }
    localStorage.setItem('iccidCardList',JSON.stringify(iccidCardListObj));
    if(iccidCardListObj[iccid] && iccid){
      return iccidCardListObj[iccid];
   
    }else{
      return false
    }
  }
}
export function setLocCardInfo(info: any,iccid:string) { 
  const iccidCardList = localStorage.getItem('iccidCardList');
  info.timer = dayjs().valueOf();
  if (iccidCardList) { 
    const iccidCardListObj = JSON.parse(iccidCardList);
    iccidCardListObj[info.iccid] = info;
    localStorage.setItem('iccidCardList', JSON.stringify(iccidCardListObj));
  }else{
    localStorage.setItem('iccidCardList', JSON.stringify({[iccid]:info}));
  }
}
/// 验证身份证号
export function validateCardId(cardId: string) {
  if (cardId.length !== 18) {
    return false; // 位数不够
  }
  // 身份证号码正则
  let postalCode = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|[Xx])$/;
  // 通过验证，说明格式正确，但仍需计算准确性
  if (!postalCode.test(cardId)) {
    return false;
  }
  //将前17位加权因子保存在数组里
  let idCardList = ['7', '9', '10', '5', '8', '4', '2', '1', '6', '3', '7', '9', '10', '5', '8', '4', '2'];
  //这是除以11后，可能产生的11位余数、验证码，也保存成数组
  let idCardYArray = ['1', '0', '10', '9', '8', '7', '6', '5', '4', '3', '2'];
  // 前17位各自乖以加权因子后的总和
  let idCardWiSum = 0;

  for (let i = 0; i < 17; i++) {
    let subStrIndex = parseInt(cardId.substring(i, i + 1));
    let idCardWiIndex = parseInt(idCardList[i]);
    idCardWiSum += subStrIndex * idCardWiIndex;
  }
  // 计算出校验码所在数组的位置
  let idCardMod = idCardWiSum % 11;
  // 得到最后一位号码
  let idCardLast = cardId.substring(17, 18);
  //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
  if (idCardMod === 2) {
    if (idCardLast !== 'x' && idCardLast !== 'X') {
      return false;
    }
  } else {
    //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
    if (idCardLast !== idCardYArray[idCardMod]) {
      return false;
    }
  }
  return true;
}

export async function copyToClipboard(text: string, onSuccess?: () => void) {
  if (!text) {
    return Message.warning('内容为空,不可复制');
  }
  return window.parent.postMessage({ type: 'copy', message: text }, '*');
  // let copyOk = false;
  // try {
  //   // 使用现代的剪贴板 API
  //   await navigator.clipboard.writeText(text);
  //   if (onSuccess) {
  //     // onSuccess();
  //   } else {
  //     Message.success('复制成功');
  //   }
  //   copyOk = true;
  // } catch (error) {
  //   // Message.error('复制失败，请重试');
  // }
  // if (!copyOk) {
  //   let div = document.createElement('div');
  //   document.body.appendChild(div);
  //   const root = ReactDOM.createRoot(div);
  //   root.render(
  //     <div className={`copy-to-clipboard`}>
  //       <textarea id="copyToClipboard" defaultValue={text} className="text-area"></textarea>
  //     </div>
  //   );
  //   await delay(200);
  //   let ta: HTMLTextAreaElement | null = document.getElementById('copyToClipboard') as HTMLTextAreaElement | null;
  //   if (ta) {
  //     ta.select();
  //     let res = document.execCommand('copy');
  //     if (res) {
  //       if (onSuccess) {
  //         onSuccess();
  //       } else {
  //         Message.success('复制成功');
  //       }
  //     }
  //   }
  //   await delay(500);
  //   root.unmount();
  //   document.body.removeChild(div);
  // }
}
// 将对象中的key改为小写
export function lowerJSONKey(jsonObj: any) {
  let newObj: any = Object.fromEntries(Object.entries(jsonObj).map(([k, v]) => [k.toLowerCase(), v]));
  return newObj;
}
// 验证是否为blob格式
export async function blobValidate(data: any) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}
